package com.agilegroup.crm.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.view.MenuItem;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.model.EmployeeData;
import com.agilegroup.crm.requests.UserLoginJsonRequest;
import com.agilegroup.crm.ui.actions.MenuHandler;
import com.agilegroup.crm.ui.fragments.ConnectionDialogFragment;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class LoginActivity extends BaseActivity {
	
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
	private String mEmail;
	private String mPassword;
	private EditText mEmailView;
	private EditText mPasswordView;
	private SessionManager session;
	private OnlineChecker checker;
	private static final String JSON_CACHE_KEY = "login_json";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		checker = new OnlineChecker(this);
        session = new SessionManager(getApplicationContext());
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});


		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						attemptLogin();
					}
				});
	}

	public void attemptLogin() {
		mEmailView.setError(null);
		mPasswordView.setError(null);

		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			focusView.requestFocus();
		} else {
			ArrayList<String> params = new ArrayList<String>();
			params.add(new String(mEmail));
			params.add(new String(mPassword));
			if(checker.isOnline()==true){
				AgileApplication.getInstance().spiceManager.execute(new UserLoginJsonRequest(params),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new UserLoginJsonRequestListener());
			}
			else{
				SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
    			dialogFragment.show(getSupportFragmentManager(), "connectionDialog");
			}
			
		}
	}
	
	public class UserLoginJsonRequestListener implements RequestListener<EmployeeData>{

		public void onRequestFailure(SpiceException spiceException) {
			Toast.makeText(LoginActivity.this, "Please,Check your Account Information", Toast.LENGTH_SHORT).show();
		}
		public void onRequestSuccess(EmployeeData data) {
			if(data!=null){
				String empId = data.getEmployeeId();
				Log.d("EMPID", empId);
				session.createLoginSession(mEmail, mPassword,empId);
				Intent mainActivity = new Intent(LoginActivity.this, MainActivity.class);
	            Toast.makeText(LoginActivity.this, "You Have Successfully Loged in", Toast.LENGTH_SHORT).show();
	            startActivity(mainActivity);
				finish();
			}
			else{
				mPasswordView.setError(getString(R.string.error_incorrect_password));
				mPasswordView.requestFocus();
			}
		}
	 }
	@Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        getSupportMenuInflater().inflate(R.menu.login, menu);
        return super.onCreateOptionsMenu(menu);
    }
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		MenuHandler.handleOnItemSelected(item, this);
		return super.onOptionsItemSelected(item);
	}
}
